/*************************************************
 *FileName:      attestantion.js
 *Description:   个人认证.js
 *Others:        陈灿
 *************************************************/
    /*
     * 启动
     */
    mui.init();
    mui('.mui-scroll-wrapper').scroll({
        indicators: false,      //是否显示滚动条 默认为true
        deceleration: 0.003,    //阻尼系数,系数越小滑动越灵敏 默认0.0006
        bounce: false           //是否启用回弹 默认true
    });
    mui.init({
        beforeback: function() {
            var list = plus.webview.currentWebview().opener();
            mui.fire(list, 'refreshindex');
            return true;
        }
    });
    /*
     * 变量初始化
     */
    var uid = localStorage.replace_uid;
    var token = localStorage.replace_token;
    var activity_province , activity_city ,activity_district ;
    var status,video_status,video='';
    var oname = '',ophone = '', owx = '',oqq ='',orange ='',ocompany ='',oadderss ='',img ='';
    
    /*
     * 主程序
     */ 
    $(document).ready(function() 
    {
        //样式加载
        pagecss();
    });
    /**
     * pagecss
     * 样式加载
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    
    var server = "http://replace-i.oss-cn-hangzhou.aliyuncs.com/";  //申请到的阿里云OSS地址
                    
    var OSSAccessKeyId= 'LTAIyJPvdRXd1eX9';     //申请到的阿里云AccessKeyId和AccessKeySecret
    var AccessKeySecret= 'Wkwdr687sxx0nK5RfWh5NiETPBAme3';//需要用自己申请的进行替换
    var files = [];  //存储文件信息的数组
    var fname = "";  //表示文件名，例如  XXXX.jpg;
    var dir ="app/";  //指定上传目录，此处指定上传到app目录下
    
    var testName;   //本地测试用的
    /*
     * 阿里云参数设置，用于计算签名signature
     */
    var policyText = {
        "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
        "conditions": [
            ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
        ]
    };
    var policyBase64 = Base64.encode(JSON.stringify(policyText));
    var message = policyBase64;
    var bytes = Crypto.HMAC(Crypto.SHA1, message, AccessKeySecret, {
        asBytes: true
    });
    var signature = Crypto.util.bytesToBase64(bytes);

    //得到文件名的后缀
    function get_suffix(filename) {
        var pos = filename.lastIndexOf('.');
        var suffix = '';
        if(pos != -1) {
            suffix = filename.substring(pos)
        }
        return suffix;
    }

    // 拍照添加文件
    function appendByCamera() {
        plus.camera.getCamera().captureImage(function(p) {
            appendFile(p);
        });
    }
    // 从相册添加文件
    function appendByGallery() {
        plus.gallery.pick(function(p) {
            appendFile(p);
        });
    }
    // 添加文件
    var index = 1;

    function appendFile(p) {
        var fe = document.getElementById("files");
        // var li = document.createElement("li");
        // var n = p.substr(p.lastIndexOf('/') + 1);
        // fname = n;
        // li.innerText = n;
        // fe.appendChild(li);
        files.push({
            name: "uploadkey" + index,
            path: p
        });
        index++;
        // empty.style.display = "none";
    }
    
    function videoUpload() {    //视频上传
        if(files.length <= 0) {
            // plus.nativeUI.alert("没有添加上传文件！");
            return;
        }
        // common.loadingIn();
//         mui.toast('开始上传：',{ duration:2000, type:'div' });
        // outSet("开始上传：")

        // var wt = plus.nativeUI.showWaiting();
        var task = plus.uploader.createUpload(server, {
                method: "POST"
            },
            function(t, status) { //上传完成
                console.log("t" + JSON.stringify(t));
                if(status == 200) {
                    mui.toast('上传成功',{ duration:2000, type:'div' });
                    // outLine("上传成功：" + t.responseText);
                    //至此上传成功，上传后的图片完整地址为server+testName
                    var uploaderFileObj = {
                        "server":server,
                        "path":testName
                    };
                    files = [];
                    console.log(t.responseText);
                    plus.storage.setItem("uploader", JSON.stringify(uploaderFileObj));
                    console.log(uploaderFileObj.path);
                    // upData.url = 'https://old-ali87.oss-cn-hangzhou.aliyuncs.com/'+uploaderFileObj.path;
                    // upData.thumb = 'http://old-ali87.oss-cn-hangzhou.aliyuncs.com/'+uploaderFileObj.path+'?x-oss-process=video/snapshot,t_1,f_jpg,w_0,h_0,m_fast';
                    // upData.type='video';
                    videoVerifyAdd(uploaderFileObj.path);
                    
                } else {
                    common.loadingOut();
                    mui.toast('上传失败：' + status,{ duration:2000, type:'div' });
                }
            }
        );
        var suffix1 = get_suffix(fname);  //文件后缀  例如   .jpg
        var keyname = dir + new Date().getTime() + suffix1;
        testName = keyname;
        
        //按照之前说明的参数类型，按顺序添加参数
        task.addData("key", keyname);
        task.addData("policy", policyBase64);
        task.addData("OSSAccessKeyId", OSSAccessKeyId);
        task.addData("success_action_status", "200");
        task.addData("signature", signature);
        var f = files[0];
        var filename=files[0].path;
        var index1=filename.lastIndexOf("."); 
        var index2=filename.length;
        var index3=filename.lastIndexOf("?");
        if(index3 > 0){
            var postf=filename.substring(index1+1,index3);//后缀名 
        }else{
            var postf=filename.substring(index1+1,index2);//后缀名 
        }
        
        task.addFile(f.path, {
            key: "file",
            name: "file",
            mime: "video/"+postf
        });

        task.start();
    }
    
    function videoVerifyAdd(video_url){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME +'/index.php/api/users_verify/videoVerifyAdd' ,
            dataType:'jsonp',
            data: {url:video_url,uid:uid},
            success: function(data) {
                common.loadingOut();
                if(data.error_code == 0){
                    mui.alert('视频认证已提交平台，请等待审核！','提示','确定',function(){ 
                         setTimeout(function(){mui.back()},500);
                    },'div');
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                    mui.alert('视频认证已提交失败！','提示','确定',function(){ 
                    },'div');
                }
            }
        });
    }
    
    function pagecss(){
        if(localStorage.replace_sex=='woman'){
            $('.content-img').html('<img src="images/gilr.png"><p class="content-p">示范照片</p>')
        }else{
            $('.content-img').html('<img src="images/boy.png"><p class="content-p">示范照片</p>')
        }
        mui.plusReady(state)  
//      state();

        //input输入的时候输入框跟着弹上去
        $('input').on('click', function () {
            var target = this;
            $(".mui-content").css('-webkit-overflow-scrolling','auto'); 
            setTimeout(function(){
                target.scrollIntoViewIfNeeded();
                $(".mui-content").css('-webkit-overflow-scrolling','touch');
                console.log('scrollIntoViewIfNeeded');
            },400);
        }); 
        
        $('.attestation').on('tap','.cancel',function(){
            if(status==''||status==2||status==3){
                var opart =$(this).parent();
                opart.hasClass('add-img') ? opart.before('<div class="add-img" onclick="captureImage()"><p class="text"><span>1</span></span>/1</p></div>'): opart.before('<div class="add-video" onclick="videos()"><div class="video-bg"></div></div>');
                opart.remove();
                return false;
            }
        })
        
        $('.add-img').on('tap',function(){
            if(status==''||status==2||status==3){captureImage()}
        })
        
        $('.add-video').on('tap',function(){
            if(video_status=='0'){
                $('.add-video').removeAttr('onclick');
                mui.toast('上次认证正在审核中！');
            }else{
                videos();
            }
        }) 
        
        var _getParam = function(obj, param) {return obj[param] || '';};
        var cityPicker3 = new mui.PopPicker({layer: 3});
        cityPicker3.setData(cityData3);
        $('.personal').on('focusin','.range2', function(e) {
            $(this).blur();
            cityPicker3.show(function(items) {
                activity_province = _getParam(items[0], 'text');
                activity_city = _getParam(items[1], 'text');
                activity_district = _getParam(items[2], 'text');
                $('.range').val(activity_province+'-'+activity_city+'-'+activity_district);
            });
        })
        
    }
    /**
     * upload
     * 上传
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    
       
    $('.rdntn').on('tap',function(){
        if($(this).hasClass('rmcolor')){
            return false;
        }else if((status==1||status=='0')&&video_status!='0'){
            if(!$('.add-video video').attr('src')){
                mui.toast('请上传认证视频');
                return false;
            }else{
                video = $('.add-video video').attr('src');
                videoUpload();
                common.loadingIn();
            }
        }else{
            oname = $('.name').val();
            ophone = $('.phone').val();
            owx = $('.wx').val();
            oqq = $('.qq').val();
            orange = $('.range').val();
            ocompany = $('.company').val();
            oadderss = $('.adderss').val();
            img = $('.add-img img').attr('src');
            if($('.add-video video').attr('src')){
                video = $('.add-video video').attr('src');
            }
            if(!oname){
                mui.toast('请输入真实姓名！');
                return false; 
            }else if(!(/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(ophone) ) ){ //判断手机号
                mui.toast('请输入正确手机号码！');
                return false; 
            }else if(!owx){
                mui.toast('请输入微信号！');
                return false; 
            }else if(!orange){
                mui.toast('请选择活动范围！');
                return false; 
            }else if(!img){
                mui.toast('请上传认证照片！');
                return false; 
            }else{
                common.loadingIn();
                mymsgup();
            }
        }
    })
    function mymsgup(){
        var task = plus.uploader.createUpload(DOMAIN_NAME + "/index.php/api/users_verify/verifyadd",
        { method:"POST",blocksize:20480,priority:100 },
            function (t, status) { //上传完成
                common.loadingOut();
                JSON.stringify(t)
                JSON.stringify(status)
                if (status == 200) {
                    mui.toast('个人认证上传成功',{ duration:2000, type:'div' });
                    videoUpload();
                }else{
                    mui.toast('个人认证上传失败',{ duration:2000, type:'div' });
                }
            }
        );
        common.loadingIn();
        task.addData("name", oname);
        task.addData("uid", uid);
        task.addData("token",token);
        task.addData("phone", ophone);
        task.addData("wx", owx);
        task.addData("qq", oqq);
        task.addData("open", orange);
        task.addData("activity_province", activity_province);
        task.addData("activity_city", activity_city);
        task.addData("activity_district", activity_district);
        task.addData("work_unit", ocompany);
        task.addData("work_address", oadderss);
        task.addFile(img, {key: "img"});
        task.addData("type", "0");
        mui.toast('开始上传',{ duration:2000, type:'div' });
        task.start();
    }
    
    function vdoup(){
        var task = plus.uploader.createUpload(DOMAIN_NAME + "/index.php/api/users_verify/verifyadd",
        { method:"POST",blocksize:20480,priority:100 },
            function (t, status) { //上传完成
                common.loadingOut();
                JSON.stringify(t)
                JSON.stringify(status)
                if (status == 200) {
                    mui.alert('视频认证已提交平台，请等待审核！','提示','确定',function(){ 
                        setTimeout(function(){mui.back()},500);
                    },'div');
                }else{
                    mui.toast('上传失败',{ duration:2000, type:'div' });
                }
            }
        );
        common.loadingIn();
        task.addData("uid", uid);
        task.addData("token",token);
        task.addData("type", '2');
        task.addFile(video, {key: "video"});
        mui.toast('开始上传',{ duration:2000, type:'div' });
        task.start();
    }
    /**
     * 
     * mui框架时间样式
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    //状态获取
    function state(){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + "/index.php/api/users_verify/UsersVerify",
            dataType:'jsonp',
            data: { uid: uid, token: token,type : 0},
            success: function(data) {
                if(data.error_code == 0){
                    status =data.data.status;
                    if(status!=3&&status!=2){
                        $('.personal input').attr('readonly','readonly');
                        $('.range').removeClass('range2');
                    }
                    $('.name').val(data.data.name);
                    $('.phone').val(data.data.phone);
                    $('.wx').val(data.data.wx);
                    data.data.qq ==''?$('.qq').val(' '):$('.qq').val(data.data.qq);
                    $('.range').val(data.data.activity_province+'-'+data.data.activity_city+'-'+data.data.activity_district);
                    activity_province=data.data.activity_province;
                    activity_city=data.data.activity_city;
                    activity_district=data.data.activity_district;
                    data.data.work_unit ==''?$('.company').val(' '):$('.company').val(data.data.work_unit);
                    data.data.work_address ==''?$('.adderss').val(' '):$('.adderss').val(data.data.work_address);
                    $('.add-img').html('<img src="'+DOMAIN_NAME+data.data.img+'"/><i class="cancel"></i>');
                    $('.content-img').remove();
                    if(data.data.video){
                        $('.add-video').html('<div class="shade"><em class="video-em"></em></div><video class="add" src="'+DOMAIN_NAME+data.data.video+'"/></video></a><i class="cancel"></i>');
                    }
                    video_status=data.data.video_status;
                    if((status==1||status=='0')&&$('.add-video video').attr('src')){
                        $('.rdntn').addClass('rmcolor');
                    }
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                    
                }
            }  
        });
    }
    
    //摄像
    function videos(){
        localStorage.camopen="false";
        common.videoCapture(function(src){
            var img = '<div class="shade"><em class="video-em"></em></div><video class="add" src="'+src+'"/></video></a><i class="cancel"></i>';
            $('.add-video').html(img); 
            appendFile(src);
            if(video_status!='0'&&status=='1'){
                $('.rdntn').removeClass('rmcolor');
            }
        })
    }
    
    //拍照和相册
    function captureImage(){
        localStorage.camopen="false";
        common.cameraImg(function(src){
            $('.add-img').html('<img src="'+src+'"/><i class="cancel"></i>');
        })
    }
